// +build edge

package thingapi

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"iot-base/common/webapi"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type loginInfo struct {
	UName string `json:"un"`
	Pswd  string `json:"pd"`
}

func proxy(c *gin.Context) {
	username := c.Query("un")
	password := c.Query("pd")
	addr := c.Query("addr")
	path := c.Query("path")
	var jsonObj interface{}
	jsonmap := make(map[string]interface{}) //注意该结构接受的内容
	jsonObj = jsonmap
	errBind := c.ShouldBindBodyWith(&jsonObj, binding.JSON)
	if errBind != nil {
		fmt.Println("*****************", errBind)
		var jsonObjArray []map[string]interface{}
		c.ShouldBindBodyWith(&jsonObjArray, binding.JSON)
		jsonObj = jsonObjArray

	}
	//fmt.Println("-----------------proxy json-------", jsonObj)
	if addr == "" {
		webapi.SendError("addr param is missed", webapi.ParamMissed, c)
		return
	}
	if !strings.Contains(addr, "http://") {
		addr = "http://" + addr
	}
	url := addr + "/api/su/login"

	linfo := loginInfo{
		UName: username,
		Pswd:  password,
	}
	bytesData, _ := json.Marshal(linfo)
	resp, rerr := http.Post(url, "application/json", bytes.NewReader(bytesData))
	if resp != nil {
		defer resp.Body.Close()
		body, _ := ioutil.ReadAll(resp.Body)
		sre := string(body)
		if strings.Contains(sre, "error") {
			webapi.SendRawData(sre, c)
			return
		}
		if !strings.HasPrefix(path, "/") {
			path = "/" + path
		}
		url = addr + path
		var bytejson []byte
		if jsonObj != nil {
			var err error
			bytejson, err = json.Marshal(&jsonObj)
			//fmt.Println("_------prox--------------2---", bytejson, err)
			if err != nil {
				fmt.Println("_------proxy------", err)
			}
		}
		reader := bytes.NewBuffer(bytejson)
		reqToCloud, _ := http.NewRequest(c.Request.Method, url, reader)
		if reqToCloud != nil {
			for _, cookie := range resp.Cookies() {
				reqToCloud.AddCookie(cookie)
			}
			querys := c.Request.URL.Query()
			if querys != nil {
				q := reqToCloud.URL.Query()
				for k, v := range querys {
					if k == "un" || k == "pd" || k == "addr" || k == "path" {
						continue
					}
					q.Add(k, v[0])
				}
				reqToCloud.URL.RawQuery = q.Encode()
			}
			reqToCloud.Header.Set("Content-Type", "application/json")

			client := &http.Client{}
			req, err := client.Do(reqToCloud)
			if err != nil {
				webapi.SendError(err.Error(), webapi.ProxyError, c)
				return
			}
			if req != nil {
				bodyProxy, _ := ioutil.ReadAll(req.Body)
				defer req.Body.Close()
				webapi.SendRawData(string(bodyProxy), c)
				return
			}

		}

	} else {
		//fmt.Println("resp is nil", url)
		webapi.SendError("response is nil "+rerr.Error(), webapi.ProxyError, c)
	}
}

func InitFromCloudAPI(cfg *gin.RouterGroup) {
	cloud := cfg.Group("cloud")
	{
		cloud.GET("/proxy", func(c *gin.Context) {
			proxy(c)
		})
		cloud.POST("/proxy", func(c *gin.Context) {
			proxy(c)
		})
		cloud.PUT("/proxy", func(c *gin.Context) {
			proxy(c)
		})
		cloud.DELETE("/proxy", func(c *gin.Context) {
			proxy(c)
		})
	}
}
